#!/usr/bin/ruby
require "rubygems"
require "opengl"
require "glut"
require "m3g"
require "pp"

class MyGLUTWidget
  def initialize
    GLUT.Init
    GLUT.InitWindowSize  256, 256
    GLUT.InitDisplayMode GLUT::GLUT_DOUBLE | GLUT::GLUT_RGB | GLUT::GLUT_DEPTH
    GLUT.CreateWindow "Ruby-M3G"

    initialize_scene

    GLUT.ReshapeFunc  method(:reshape).to_proc()
    GLUT.DisplayFunc  method(:display).to_proc()
    GLUT.KeyboardFunc method(:keyboard).to_proc()
    GLUT.MouseFunc    method(:mouse).to_proc()
    GLUT.IdleFunc     method(:idle).to_proc()

  end

  def initialize_scene

    objs = M3G::Loader::load "cube.m3g"
    objs = nil
    GC.start
    objs = M3G::Loader::load "cube.m3g"

    objs.each { |obj|
      if obj.instance_of? M3G::World
        @wld = obj 
      end
    }
    puts "CAUTION: can't find World" if !@wld

    bg = M3G::Background.new
    bg.color = 0x7f3f7fff
    @wld.background = bg

    @world_time = 0
  end

  def display
    g3d = M3G::Graphics3D::instance
    g3d.render @wld
    GLUT.SwapBuffers()
  end
  
  def reshape width, height
    g3d = M3G::Graphics3D::instance
    g3d.viewport = 0,0,width,height
    @wld.active_camera.perspective = 45, width/(height*1.0), 0.1, 1000
  end

  def keyboard key, x, y
    if key == 113
      exit
    end
  end

  def mouse button, state, x, y
  end

  def idle
    @world_time = (@world_time + 70) % 5000
    @wld.animate @world_time
    puts "main: time = #{@world_time}"
    GLUT.PostRedisplay
  end

  def start
    GLUT.MainLoop
  end

end


MyGLUTWidget.new.start

